package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.relultObjects.FullRace;
import ua.races.vo.BetType;
import ua.races.vo.Horse;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class AddHorseCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(AddHorseCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        RacesDaoImpl dao = null;
        List<Horse> horses = null;
        Horse horse = null;
        String horseName = null;
        String redirectUrl = null;
        String message = null;


        try {
            message = "Sorry, you had inputted horse which is already exist in the db" +
                    " and it has not been successfully added (((";
            redirectUrl = req.getHeader("referer");

            dao = (RacesDaoImpl) context.getAttribute("DAO");
            horseName = req.getParameter("horseName").trim();
            horses = dao.findAllHorses();

            for (Horse h : horses) {
                if (h.getHorseName().equalsIgnoreCase(horseName) || (horseName.matches("^\\s*$"))) {
                    throw new IllegalArgumentException("trying to add an existing horse");
                }
            }
            horse = new Horse();
            horse.setHorseName(horseName);
            dao.addNewHorse(horse);
            message = "Horse : " + horseName + " has been successfully added to db!";
            redirectUrl = "prepareAdmin.do";
        } catch (SQLException e) {
            log.error(e);
        } catch (Throwable e) {
            log.error(e);
        } finally {
            try {
                req.setAttribute("URL", redirectUrl);
                req.setAttribute("message", message);
                context.getRequestDispatcher("/redirection.jsp").forward(req, resp);
            } catch (ServletException e) {
                log.fatal(e);
            } catch (IOException e) {
                log.fatal(e);
            }
        }

    }


}
